package com.devmarvel.creditcardentry.fields;

import com.devmarvel.creditcardentry.ResourceTable;
import com.devmarvel.creditcardentry.internal.CreditCardUtil;
import com.devmarvel.creditcardentry.library.CardType;
import com.devmarvel.creditcardentry.util.LogUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

public class CreditCardText extends CreditEntryFieldBase {

	private CardType type;

	private String mHelperText;

	public CreditCardText(Context context) {
		super(context);
		init();
	}

	public CreditCardText(Context context, AttrSet attrs) {
		super(context, attrs);
		init();
	}

	public CreditCardText(Context context, AttrSet attrs, String defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	@Override
	void init() {
		super.init();
		setTextAlignment(TextAlignment.LEFT | TextAlignment.VERTICAL_CENTER);
	}

	/* TextWatcher Implementation Methods */
	@Override
	public void afterTextChanged(String s) {
		if (s.length() >= CreditCardUtil.CC_LEN_FOR_TYPE) {
			formatAndSetText(s);
		} else {
			if (this.type != null) {
				this.type = null;
				delegate.onCardTypeChange(CardType.INVALID);
			}
		}
	}

	public void formatAndSetText(String number) {
		CardType type = CreditCardUtil.findCardType(number);

		if (type.equals(CardType.INVALID)) {
			setValid(false);
			delegate.onBadInput(this);
			return;
		}

		if (this.type != type) {
			delegate.onCardTypeChange(type);
		}
		this.type = type;
		LogUtil.error("Card type:", this.type.toString());

		String formatted = CreditCardUtil.formatForViewing(number, type);
		LogUtil.error("Formatted:", formatted);
		if (!number.equalsIgnoreCase(formatted)) {
			watcherEnabled = false;
			this.setText(formatted);
			watcherEnabled = true;
		}

		if (formatted.length() >= CreditCardUtil.lengthOfFormattedStringForType(type)) {

			String remainder = null;
			if (number.startsWith(formatted)) {
				remainder = number.replace(formatted, "");
			}
			if (CreditCardUtil.isValidNumber(formatted)) {
				setValid(true);
				delegate.onCreditCardNumberValid(remainder);
			} else {
				setValid(false);
				delegate.onBadInput(this);
			}
		} else {
			setValid(false);
		}
	}

	public CardType getType() {
		return type;
	}

	@Override
	public void setHelperText(String helperText) {
		mHelperText = helperText;
	}

	@Override
	public String getHelperText() {
		return (mHelperText != null ? mHelperText : context.getString(ResourceTable.String_CreditCardNumberHelp));
	}
}
